package com.ds.iot.comet;

import com.ds.common.JDSException;
import com.ds.context.JDSCometContext;
import com.ds.context.JDSContext;
import com.ds.engine.ConnectInfo;
import com.ds.engine.ConnectionHandle;
import com.ds.engine.JDSSessionHandle;
import com.ds.iot.client.GatewayWebService;
import com.ds.iot.json.device.Gateway;
import com.ds.jds.core.esb.EsbUtil;
import com.ds.msg.Msg;
import com.ds.server.JDSClientService;
import com.ds.server.JDSServer;
import com.ds.server.comet.AbstractCometHandle;
import com.ds.server.eumus.ConfigCode;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Set;

public class GWCometHandle extends AbstractCometHandle {

    public GWCometHandle(JDSClientService client, JDSSessionHandle sessionHandle, String systemCode) throws JDSException {
        super(client, sessionHandle, systemCode);

    }

    public void receive(String receiveStr) throws JDSException {
        logger.info("receive user:[" + getConnectInfo().getLoginName() + "] ");
        logger.info(receiveStr);
    }

    public boolean send(String msgString) throws JDSException {
        logger.info(msgString);
        return super.send(msgString);
    }

    class ClearSession implements Runnable {
        private ConnectionHandle sessionHandle;

        private ConnectInfo connectInfo;

        private String systemCode;

        ClearSession(ConnectInfo connectInfo, ConnectionHandle handle, String systemCode) {
            this.sessionHandle = handle;
            this.connectInfo = connectInfo;
            this.systemCode = systemCode;
        }

        public void run() {
            try {
                Set<JDSSessionHandle> sessionHandleList = JDSServer.getInstance().getSessionHandleList(connectInfo);
                for (JDSSessionHandle handle : sessionHandleList) {
                    if (!handle.toString().equals(sessionHandle.toString())) {
                        JDSClientService client = JDSServer.getInstance().getJDSClientService(handle, ConfigCode.app);
                        if (client != null && client.getConnectInfo() != null) {
                            client.getConnectionHandle().disconnect();
                        }
                    }

                }
            } catch (JDSException e) {
                e.printStackTrace();
            }

        }

    }

    public void connect(JDSContext context) throws JDSException

    {

        if (context instanceof JDSCometContext) {
            JDSCometContext cometContext = (JDSCometContext) context;
            this.request = (HttpServletRequest) cometContext.getHttpRequest();
            this.response = (HttpServletResponse) cometContext.getHttpResponse();
        } else {
            throw new JDSException("用户未登录！", JDSException.PROCESSDEFINITIONERROR);
        }

        if (this.connectInfo == null) {
            connectInfo = this.getClient().getConnectInfo();
        }

        if (this.connectInfo == null) {
            throw new JDSException("用户未登录！", JDSException.PROCESSDEFINITIONERROR);
        }


        sessionMapUser.put(sessionHandle.getSessionID(), connectInfo.getUserID());
        logger.info("sessionMapUser: sessionid=" + sessionHandle.getSessionID() + " userid=" + connectInfo.getUserID());

        client.connect(connectInfo);
        logger.info("user:" + connectInfo.getLoginName() + "[" + sessionHandle.getSessionID() + "] cometLogin success");
     
        while (isClose) {
            JDSClientService client = this.getClient();
            ConnectInfo connectionInfo = client.getConnectInfo();
            if (client != null && connectionInfo != null) {

                Long lastLoginTime = checkTime.get(context.getSessionId());
                Long lastCommandTime = checkHeart.get("Herat" + context.getSessionId() + "");

                if (lastCommandTime == null) {
                    lastCommandTime = System.currentTimeMillis();
                    checkHeart.put("Herat" + context.getSessionId() + "", lastCommandTime);

                }

                Long lastHeartTime = checkCommandHeart.get(context.getSessionId());


                if (lastLoginTime == null) {
                    lastLoginTime = System.currentTimeMillis();
                    checkTime.put(context.getSessionId(), lastLoginTime);
                    ConnectionServer connectTask = new ConnectionServer(client, connectInfo);

                    getCommandService(connectInfo.getUserID()).submit(connectTask);
                }

                if (System.currentTimeMillis() - lastLoginTime > 30 * 1000) {
                    checkTime.put(context.getSessionId(), System.currentTimeMillis());
                    ConnectionServer connectTask = new ConnectionServer(client, connectInfo);

                    getCommandService(connectInfo.getUserID()).submit(connectTask);
                }

                send(HEARTKEY);
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    isClose = false;
                    send(e.getMessage());

                }
    
            } else {
                isClose = false;

                send("sessionId is  null,  place login frist!");
                this.disconnect();
            }
        }

    }

    public void disconnect() throws JDSException {
        try {
             GatewayWebService gwclient=(GatewayWebService)
             EsbUtil.parExpression("$GatewayWebService");
             Gateway gateway=new Gateway();
             gateway.setDeviceId(connectInfo.getLoginName());
             gateway.setGatewayAccount(connectInfo.getLoginName());
             gwclient.gatewayOffLine(gateway);

        } catch (Exception e) {
            logger.error(e);
        }

        super.disconnect();
    }

    @Override
    public boolean repeatMsg(Msg msg, JDSSessionHandle handle) throws JDSException {
        // TODO Auto-generated method stub
        return false;
    }
}
